package httpHandler

import (
	baseHttp "gitee.com/zaiqiang231/go-base-app/base_app/http"
	sessionModel "gitee.com/zaiqiang231/go-base-session/app/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	KEY_ATOM = "atom"
)

// Cors 跨域处理
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			// 当Access-Control-Allow-Credentials为true时，将*替换为指定的域名
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "*")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Header("Access-Control-Max-Age", "86400") // 可选
			c.Set("content-type", "application/json")   // 可选
		}

		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		c.Next()
	}
}

// AtomFunc 原子参数
func AtomFunc(c *gin.Context) {
	var atom sessionModel.Atom
	if err := c.ShouldBindQuery(&atom); err != nil {
		baseHttp.WriteResponse(c, http.StatusBadRequest, err.Error(), nil)
		return
	}
	c.Set(KEY_ATOM, atom)
	c.Next()
}

func GetAtom(c *gin.Context) (atom sessionModel.Atom) {
	if val, ok := c.Get(KEY_ATOM); ok && val != nil {
		atom, _ = val.(sessionModel.Atom)
	}
	return
}
